package com.getpebble.android.jskit.concurrency;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncStepRunnable implements Runnable {
    protected Lock mCvLock = new ReentrantLock();
    protected Condition mCvWait = this.mCvLock.newCondition();
    protected Runnable mProxiedRunnable;
    protected long mRunnerThreadId = -1;
    protected AtomicBoolean mRunnerThreadIdValid = new AtomicBoolean(false);

    protected SyncStepRunnable() {
    }

    public static SyncStepRunnable newRunnable(Runnable r) {
        if (r == null) {
            return null;
        }
        SyncStepRunnable newInst = new SyncStepRunnable();
        newInst.mProxiedRunnable = r;
        return newInst;
    }

    public void run() {
        this.mRunnerThreadId = Thread.currentThread().getId();
        this.mRunnerThreadIdValid.set(true);
        this.mProxiedRunnable.run();
        this.mCvLock.lock();
        this.mCvWait.signalAll();
        this.mCvLock.unlock();
    }

    public boolean waitForRunToFinish(boolean uninterruptable) {
        boolean interrupted = false;
        do {
            if (uninterruptable) {
                try {
                    this.mCvLock.lock();
                    this.mCvWait.awaitUninterruptibly();
                } catch (InterruptedException e) {
                    interrupted = true;
                } catch (Exception e2) {
                }
            } else {
                this.mCvLock.lockInterruptibly();
                this.mCvWait.await();
            }
            interrupted = false;
            this.mCvLock.unlock();
            if (!uninterruptable) {
                break;
            }
        } while (interrupted);
        if (interrupted) {
            return false;
        }
        return true;
    }
}
